package com.wxx.exception;

import com.wxx.util.JsonData;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 * @ControllerAdvice  @ExceptionHandler(value = Exception.class)
 */
@ControllerAdvice
public class TotalExceptionHandler {

    /**
     * 全局处理后台和ajax异常
     * @param request
     * @param response
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e)throws Exception{
        e.printStackTrace();

        if(isAjax(request)){
            return JsonData.fail(e.getMessage());
        }else {
            ModelAndView mav = new ModelAndView();
            //错误内容
            mav.addObject("exception", e);
            //错误地址
            mav.addObject("url", request.getRequestURL());
            //返回的错误的页面
            mav.setViewName("error");
            return mav;
        }
    }

    /**
     * 判断是否是一个ajax请求
     * @param request
     * @return
     */
    private boolean isAjax(HttpServletRequest request) {
        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
            return true;
        } else {
            return false;
        }
    }
}
